package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Pull.MaterialPlug;
import com.ruoyi.system.domain.base.BaseShop;
import com.ruoyi.system.domain.base.ShopConfigDTO;
import com.ruoyi.system.domain.base.TreeShop;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.BaseShopMapper;
import com.ruoyi.system.service.IBaseShopService;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工厂模型Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-02
 */
@Service
public class BaseShopServiceImpl extends ServiceImpl<BaseShopMapper, BaseShop> implements IBaseShopService {

    @Override
    public List<ShopConfigDTO> selectShopConfigList(ShopConfigDTO dto) {
        List<ShopConfigDTO> baseShops = baseMapper.selectByList(dto);
        return baseShops;
    }

    @Override
    public String checkDeptNameUnique(BaseShop baseShop) {
        Long deptId = StringUtils.isNull(baseShop.getShopId()) ? -1L : baseShop.getShopId();
        BaseShop info = baseMapper.selectOne(new QueryWrapper<BaseShop>().eq("shop_name", baseShop.getShopName())
                .eq("parent_id", baseShop.getParentId()));
        if (StringUtils.isNotNull(info) && info.getShopId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertShop(BaseShop baseShop) {
        BaseShop info = baseMapper.selectOne(new QueryWrapper<BaseShop>().eq("shop_id", baseShop.getParentId()));
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("工厂停用，不允许新增");
        }
        baseShop.setAncestors(info.getAncestors() + "," + baseShop.getParentId());
        return baseMapper.insert(baseShop);
    }

    @Override
    public List<BaseShop> selectShopList(BaseShop shop) {
        QueryWrapper<BaseShop> qw = new QueryWrapper<BaseShop>();
        if(shop.getShopId()!=null){
            qw.eq("Shop_id",shop.getShopId());
        }
        List<BaseShop> shops = baseMapper.selectList(qw);
        return shops;
    }



    @Override
    public List<TreeShop> buildShopTreeSelect(List<BaseShop> shops) {
        List<BaseShop> shopTrees = buildShopTree(shops);
        return shopTrees.stream().map(TreeShop::new).collect(Collectors.toList());
    }

    @Override
    public List<BaseShop> getTreeFindType(String type) {
        List<BaseShop> shops = baseMapper.selectList(new QueryWrapper<BaseShop>().eq("shop_type", type));
        return shops;
    }

    @Override
    public List<BaseShop> getTreeFindId(Integer shopId) {
        List<BaseShop> shops = baseMapper.selectList(new QueryWrapper<BaseShop>().eq("parent_id", shopId));
        return shops;
    }

    @Override
    public BaseShop getLevel(String shopCode) {
        LambdaQueryWrapper<BaseShop> lqw = new LambdaQueryWrapper<BaseShop>();
        if(StrUtil.isNotEmpty(shopCode)){
            lqw.eq(BaseShop::getShopCode,shopCode);
        }
        return baseMapper.selectOne(lqw);
    }

    @Override
    public boolean hasChildByDeptId(Long shopId) {
        int result = baseMapper.hasChildByDeptId(shopId);
        return result > 0 ? true : false;
    }


    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    public List<BaseShop> buildShopTree(List<BaseShop> shops)
    {
        List<BaseShop> returnList = new ArrayList<BaseShop>();
        List<Long> tempList = new ArrayList<Long>();
        for (BaseShop dept : shops)
        {
            tempList.add(dept.getShopId());
        }
        for (Iterator<BaseShop> iterator = shops.iterator(); iterator.hasNext();)
        {
            BaseShop dept = (BaseShop) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(shops, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = shops;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<BaseShop> list, BaseShop t)
    {
        // 得到子节点列表
        List<BaseShop> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BaseShop tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<BaseShop> it = childList.iterator();
                while (it.hasNext())
                {
                    BaseShop n = (BaseShop) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<BaseShop> getChildList(List<BaseShop> list, BaseShop t)
    {
        List<BaseShop> tlist = new ArrayList<BaseShop>();
        Iterator<BaseShop> it = list.iterator();
        while (it.hasNext())
        {
            BaseShop n = (BaseShop) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getShopId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BaseShop> list, BaseShop t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
